﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using UnityEditor.SceneManagement;
using System.Xml;
using System.Text;

public class EasyEditor : Editor
{
    [MenuItem("Custom/GotoSetup")]
    public static void GotoSetup()
    {
        EditorSceneManager.OpenScene(Application.dataPath + "/Scenes/Setup.unity");
    }
    [MenuItem("Custom/GotoUIEditor")]
    public static void GotoUIEditor()
    {
        EditorSceneManager.OpenScene(Application.dataPath + "/Scenes/UIEditor.unity");
    }

    // 把配置文件放入Resource目录下
    [MenuItem("Custom/ConfigToResources")]
    public static void ConfigToResources()
    {
        // 找到目标路径和源路径
        // 清空目标路径
        // 把源路径内的所有文件，复制到目标路径，并添加扩展名".bytes"
        // 强制刷新
        // Directory 操作目录；File 操作文件


        var srcPath = Application.dataPath + "/../Config/";
        var dstPath = Application.dataPath + "/Resources/Config/";

        if (Directory.Exists(dstPath))
        {
            Directory.Delete(dstPath, true);
        }

        Directory.CreateDirectory(dstPath);

        foreach (var filePath in Directory.GetFiles(srcPath))
        {
            var fileName = filePath.Substring(filePath.LastIndexOf('/') + 1);
            File.Copy(filePath, dstPath + fileName + ".bytes", true);
        }

        AssetDatabase.Refresh();
        Debug.Log("配置文件复制完毕！");
    }

    public class TestExportSprite
    {

        [MenuItem("Assets/导出选中图片为单独png")]
        static void ExportSelSprite()
        {
            string resourcesPath = "Assets/Resources/";
            foreach (Object obj in Selection.objects)
            {
                string selectionPath = AssetDatabase.GetAssetPath(obj);

                // 必须最上级是"Assets/Resources/"
                if (selectionPath.StartsWith(resourcesPath))
                {
                    string selectionExt = System.IO.Path.GetExtension(selectionPath);
                    if (selectionExt.Length == 0)
                    {
                        continue;
                    }

                    // 得到导出路径
                    string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
                    loadPath = loadPath.Substring(resourcesPath.Length);

                    // 加载此文件下的所有资源
                    Sprite[] sprites = Resources.LoadAll<Sprite>(loadPath);
                    if (sprites.Length > 0)
                    {
                        // 创建导出文件夹
                        string outPath = Application.dataPath + "/outSprite/" + loadPath;
                        System.IO.Directory.CreateDirectory(outPath);

                        foreach (Sprite sprite in sprites)
                        {
                            // 创建单独的纹理
                            Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, sprite.texture.format, false, false);
                            var s = sprite.texture.GetPixels((int)sprite.rect.xMin, (int)sprite.rect.yMin,
                                (int)sprite.rect.width, (int)sprite.rect.height);
                            //for (int i = 0; i < s.Length; ++i)
                            //{
                            //    s[i].a = 0;
                            //    s[i].g = 1;
                            //    s[i].b = 0;
                            //    s[i].r = 1;
                            //}
                            tex.SetPixels(s);
                            tex.alphaIsTransparency = true;
                            tex.Apply();

                            // 写入成PNG文件
                            System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
                        }
                        Debug.Log(string.Format("Export {0} to {1}", loadPath, outPath));
                    }
                }
            }
            Debug.Log("Export All Sprites Finished");
            AssetDatabase.Refresh();
        }
    }
}

public class CustomFontMaker : EditorWindow
{

    private Font font;
    private TextAsset xmlText;

    [MenuItem("Window/CustomFontMaker")]
    static void AddWindow()
    {
        //创建窗口
        Rect wr = new Rect(0, 0, 500, 500);
        CustomFontMaker window = (CustomFontMaker)EditorWindow.GetWindowWithRect(typeof(CustomFontMaker), wr, true, "自定义字体");
        window.Show();

    }

    // Use this for initialization
    void Start()
    {

    }

    void OnGUI()
    {
        font = EditorGUILayout.ObjectField("字体", font, typeof(Font), true) as Font;
        xmlText = EditorGUILayout.ObjectField("文字XML配置", xmlText, typeof(TextAsset), true) as TextAsset;

        if (GUILayout.Button("创建字体", GUILayout.Width(200)))
        {
            this.CreateFont();
        }
    }

    void CreateFont()
    {
        XmlDocument _doc = new XmlDocument();
        byte[] _array = Encoding.ASCII.GetBytes(xmlText.text);
        MemoryStream _stream = new MemoryStream(_array);
        _doc.Load(_stream);

        XmlNode _font = _doc.SelectSingleNode("font");
        XmlElement _common = (XmlElement)_font.SelectSingleNode("common");

        float _scaleW = float.Parse(_common.GetAttribute("scaleW"));
        float _scaleH = float.Parse(_common.GetAttribute("scaleH"));

        XmlNode _chars = _font.SelectSingleNode("chars");
        XmlNodeList _charsList = _chars.ChildNodes;

        CharacterInfo[] _infos = new CharacterInfo[_charsList.Count];
        for (int i = 0; i < _charsList.Count; i++)
        {
            XmlElement _element = (XmlElement)_charsList[i];
            CharacterInfo _characterInfo = new CharacterInfo();
            _characterInfo.index = int.Parse(_element.GetAttribute("id"));

            float _x = float.Parse(_element.GetAttribute("x"));
            float _y = float.Parse(_element.GetAttribute("y"));

            int _width = int.Parse(_element.GetAttribute("width"));
            int _height = int.Parse(_element.GetAttribute("height"));

            int _xadvance = int.Parse(_element.GetAttribute("xadvance"));

            _characterInfo.uv = new Rect(_x / _scaleW, 1 - (_y + _height) / _scaleH, _width / _scaleW, _height / _scaleH);
            _characterInfo.vert = new Rect(0, 0, _width, -_height);
            _characterInfo.width = _xadvance;
            Debug.Log(_characterInfo.uv);
            _infos[i] = _characterInfo;
        }
        font.characterInfo = _infos;
    }
}